import { login, getPerson } from '@/api/login'
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import { Message } from 'element-ui'

Vue.use(Vuex)
import createPersistedState from "vuex-persistedstate"
export default new Vuex.Store({
  state: {
    isCollapse:false,
    name:"",
    token:" "
  },
  getters: {
  },
  mutations: {
    CHANGE_COLLAPSE(state){
      state.isCollapse = !state.isCollapse
    },
    SET_NAME(state, name){
      state.name = name
    },
    SET_TOKEN(state,token){
      state.token = token
    },
    RESET(state){
      state.token = ""
      state.name = ''
      localStorage.removeItem("name")
      localStorage.removeItem("token")
    }
  },
  actions: {
    collapse({commit}){
      commit("CHANGE_COLLAPSE")
    },
    //登录
    gologin({commit},data){
      login(data).then(res => {
         if (res.code == 200) { 
          localStorage.setItem("token",res.token)
          Message.success("登陆成功")
              router.push({
                path: "/home"
              })
              // commit("SET_NAME",res.data.name)
              commit("SET_TOKEN",res.token)
              // //存本地一份
             
              // localStorage.setItem("name",res.data.name)

            }  
      })
      .catch(err => {
        Message.error(err.msg)
      })
    },
    //获取个人信息
    getUserInfo({commit}){
      getPerson().then(res => {
        console.log(res,"===========")
        commit("SET_NAME", res.user.nickName)
      })
      .catch(() => {})
    },
    //退出登录
    outlogin({commit}){
      commit("RESET")
      router.push({
        path:"/login"
      })
    }
  },
  modules: {
  },
  //配置持久化插件
   plugins:[
 createPersistedState({
      //默认会存到localStorage
      storage: localStorage,
      // 存储的key名
      key: "my-key",
      // 存储指定变量
      paths:["token", "name"]
    })
  ]
})
